<template>
  <div class="User">
    <div class="page-head">
      <div class="page-title">用户管理</div>
      <div class="page-tool">
        <el-select
          v-if="false"
          placeholder="全部角色"
          class="tool-sel"
          clearable
        >
          <el-option
            v-for="item in roleSel"
            :key="item.role_id"
            :label="item.name"
            :value="item.role">
          </el-option>
        </el-select>
        <search-input placeholder="用户名搜索" @search="searchChange" />
        <div
          class="tool-btn"
          @click="open('add')"
        >
          新增用户
        </div>
      </div>
    </div>
    <div class="page-body">
      <div class="table_data">
        <el-table :data="tableData" stripe border :fit="true" :height="$tableHeight">
          
          <el-table-column
            prop="name"
            label="用户名"
          >
          </el-table-column>
          <el-table-column
            prop="role"
            label="角色"
          >
            <template slot-scope="{ row }">
              <div>
                {{row.roles.map(r => r.role_name).join(',')}}
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="140">
            <template slot-scope="{ row }">
              <div class="operation-col">
                <div
                  class="txt-btn ope-btn"
                  @click="openPwd(row)"
                >
                  <el-tooltip effect="dark" content="修改密码" placement="top-start">
                    <img src="~assets/img/password.png" alt="">
                  </el-tooltip>
                </div>
                <div
                  class="txt-btn ope-btn"
                  @click="open('update', row)"
                >
                  <el-tooltip effect="dark" content="编辑" placement="top-start">
                    <img src="~assets/img/edit.png" alt="">
                  </el-tooltip>
                </div>
                <div
                  class="txt-btn"
                  @click="doDelete(row)"
                >
                  <el-tooltip effect="dark" content="删除" placement="top-start">
                    <img src="~assets/img/delete.png" alt="">
                  </el-tooltip>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>

      </div>
      <div class="page-footer">
        <pagina-tion
          class="page-pager"
          v-show="total >= 0"
          :background="true"
          :total="total"
          :offset.sync="offset"
          :limit.sync="limit"
          @pagination="getChangePage"
          @sizeChange="getSizePage"
        />
      </div>
    </div>

    <!-- 新增和修改弹框 -->
    <el-dialog
      :visible.sync="model.visible"
      width="370px"
      :title="model.type === 'add' ? '新增用户' : '修改用户'"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="dialog-body">
        <el-form
          ref="form"
          :model="form"
          label-width="110px"
          label-position="left"
        >
          <el-form-item label="用户名" class="required">
            <el-input
              v-model="form.name"
              name="username"
              v-validate="'required'"
            />
            <div v-show="errors.has('name')" class="el-form-item__error">
              {{ errors.first("name") }}
            </div>
          </el-form-item>
          <el-form-item label="角色" class="required">
            <el-select
              class="form-sel"
              v-model="form.role_id"
              name="role"
              placeholder="请选择角色"
              v-validate="'required'"
            >
              <el-option
                v-for="item in roleSel"
                :key="item.role_id"
                :label="item.name"
                :value="item.role_id"
                :disabled="item.name === '超级管理员'"
              />
            </el-select>
            <div v-show="errors.has('role')" class="el-form-item__error">
              {{ errors.first("role") }}
            </div>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="close">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改密码弹框 -->
    <el-dialog
      v-if="passwordVisable"
      :visible.sync="passwordVisable"
      width="450px"
      title="修改密码"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="dialog-body">
        <el-form v-model="form" ref="form" label-width="90px" label-position="left">
          <el-form-item label="旧密码" class="required">
            <el-input
              v-model="pwdForm.old_password"
              v-validate="'required|onlyRule4'"
              name='oldPassword'
              type="password"
            />
            <div v-show="errors.has('oldPassword')" class="el-form-item__error">{{ errors.first('oldPassword') }}</div>
          </el-form-item>
          <el-form-item label="新密码"  class="required">
            <el-input
              ref="new_password"
              v-model="pwdForm.new_password"
              v-validate="'required|onlyRule4'"
              name='new_password'
              type="password"
            />
            <div v-show="errors.has('new_password')" class="el-form-item__error">{{ errors.first('new_password') }}</div>
          </el-form-item>
          
          <el-form-item label="确认密码" class="required">
            <el-input
              autocomplete="off"
              v-model="pwdForm.renew_password"
              v-validate="'required|confirmed:new_password|onlyRule4'"
              data-vv-as="new_password"
              name='renew_password'
              type="password"
            />
            <div v-show="errors.has('renew_password')" class="el-form-item__error">{{ errors.first('renew_password') }}</div>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closePwd">取 消</el-button>
        <el-button type="primary" @click="submitPwd">确 定</el-button>
      </span>
    </el-dialog>



    <!-- 删除弹窗 -->
    <el-dialog
      :visible.sync="visibility"
      width="430px"
      height="100px"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="dialog-content comfirm-body">
        <img class="comfirm-ico" src="~assets/img/warning.png" />
        <div class="comfirm-txt">
          <div>确定删除该条数据？</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="visibility = false">取 消</el-button>
        <el-button type="primary" @click="asyncDelete">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as api from "@/api";
import { limit, smallLimit } from "@/consts/consts";
import { userKey, pwdKey } from "@/consts/formKey";
import searchInput from "@/components/libs/searchInput";
import paginaTion from "@/components/libs/paginaTion";


export default {
  components:{
    searchInput,
    paginaTion
  },
  data() {
    return {
      limit,
      total: 0,
      offset: 0,
      tableData: [],
      roleSel: [],
      model: {
        type: "add",
        visible: false,
      },
      id: '',
      form: {
        ...userKey
      },
      pwdForm: {
        ...pwdKey
      },
      visibility: false,
      passwordVisable: false,
      password: ''
    }
  },


  methods: {
    open(type, row = null) {
      this.$validator.reset();
      this.model.type = type;
      if (row) {
        for (const k in userKey) {
          this.form[k] = row[k]
          this.form.role_id = row.roles[0].role_id
        }
        this.id = row.user_id;
      }

      this.model.visible = true;
    },

    openPwd(row) {
      this.$validator.reset();
      this.id = row.user_id
      this.passwordVisable = true
    },

    searchChange(e) {
      this.search = e;
      this.offset = 0;
      this.getList();
    },

    getChangePage(val) {
      this.offset = val.offset;
      this.getList();
    },
        
    getSizePage(val) {
      this.offset = 0
      this.getList();
    },

    close() {
      this.model.visible = false;
      this.form = { ...userKey };
    },

    submit() {
      this.$validator.validateAll().then((valid) => {
        if (valid) {
          this.addOrEdit();
        } else {
          this.$message.warning("有信息未填写正确");
        }
      });
    },

    closePwd() {
      this.passwordVisable = false
      this.pwdForm = {
        ...pwdKey
      }
    },

    doDelete(row) {
      this.id = row.user_id
      this.visibility = true
    },

    submitPwd() {
      
      this.modifypassword()
    },

    // 修改密码
    async modifypassword() {
      const { code } = await api.user(this).modifypassword({
        old_password: window.btoa(this.pwdForm.old_password),
        new_password: window.btoa(this.pwdForm.new_password),
      }, this.id)
      if (code === 0) {
        this.$message.success('操作成功')
        this.closePwd()
        this.getList()

      }
    },

    // 角色列表
    async roleList() {
      const { code, data } = await api.user(this).roleList()
      if (code === 0) {
        this.roleSel = data
      }
    },

    // 列表
    async getList() {
      const { code, data, total } = await api.user(this).getList({
        offset: this.offset,
        limit: this.limit,
        name: this.search ,
      });
      if (code === 0) {
        this.tableData = data
        this.total = total
      }
    },


    async addOrEdit() {
      let fn = this.model.type
      const { code } = await api.user(this)[fn]({
        data: this.form
      }, this.id);
      if (code === 0) {
        this.$message.success("操作成功");
        this.close();
        this.getList();
      }
    },

    async asyncDelete() {
      const { code } = await api.user(this).delete(this.id);
      if (code === 0) {
        this.$message.success("操作成功");
        this.id = "";
        this.visibility = false;
        if (this.total % this.limit === 1) {
          if (this.offset >= this.limit) {
            this.offset -= this.limit;
          }
        }
        this.getList();
      }
    },

  },
  created() {
    this.roleList()
    this.getList()
  },
};
</script>

<style lang="stylus">
.User {

}

</style>